<!DOCTYPE html>
<html lang="zh" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>武钢有限组织绩效</title>
    <link href="../static/css/todostyle.css" rel="stylesheet" th:href="@{/css/todostyle.css}"/>
    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}"/>
    <link rel="stylesheet" th:href="@{/css/font-awesome.min.css}"/>
    <!-- bootstrap-table 表格插件样式 -->
    <link rel="stylesheet" th:href="@{/ajax/libs/bootstrap-table/bootstrap-table.min.css}"/>
    <link rel="stylesheet" th:href="@{/ajax/libs/bootstrap-treetable/bootstrap-treetable.css}"/>
    <link rel="stylesheet"
          th:href="@{/ajax/libs/bootstrap-table/extensions/columns/bootstrap-table-fixed-columns.css}"/>
    <link rel="stylesheet" th:href="@{/css/animate.css}"/>
    <link rel="stylesheet" th:href="@{/css/style.css}"/>
    <link rel="stylesheet" th:href="@{/ajax/libs/select/select2.css}"/>
    <link rel="stylesheet" th:href="@{/ruoyi/css/ry-ui.css}"/>
    <style>

    </style>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form id="form-kaoping">
        <input id="id" name="id" th:value="${approver.id}" type="hidden">
        <input id="roleId" name="roleId" th:value="${roleId}" type="hidden"><!-- 待办人员角色 -->
        <input id="tableId" name="tableId" th:value="${approver.tableId}" type="hidden">
        <input id="approveorder" name="approveorder" th:value="${approver.approveorder}" type="hidden">
    </form>
    <input id="typeYB" th:value="${type}" type="hidden"/>
    <div class="container-div ui-layout-center">
        <div class="row">
            <div class="btn-group-sm" id="toolbar" role="group">
                <a onclick="insertRow()" th:class="${type==1}?'btn btn-success disabled':'btn btn-success'">
                    <i class="fa fa-plus"></i> 添加
                </a>
                <a id="remove" onclick="doRemoveById()"
                   th:class="${type==1}?'btn btn-danger disabled':'btn btn-danger'">
                    <i class="fa fa-remove"></i> 删除
                </a>
                <a onclick="doSubmit()" th:class="${type==1}?'btn btn-success disabled':'btn btn-success'">
                    <i class="fa fa-check"></i> 提交
                </a>
                <!--<a th:if="${type==1}" class="btn btn-warning" onclick="appealfun()" >
                    <i class="fa fa-gavel"></i> 申诉
                </a>-->
                <a class="btn btn-success" onclick="importExcel()" shiro:hasPermission="zzjx:indicator:import">
                    <i class="fa fa-upload"></i> 导入
                </a>
                <a class="btn btn-info" onclick="closeItem()">
                    <i class="fa fa-reply"></i> 取消
                </a>
            </div>
            <div class="evaluate_c table2excel" id="tableDiv" style="width: 98%;">
                <table data-mobile-responsive="true" id="table"></table>
            </div>
        </div>
    </div>
</div>
<div th:include="include::footer"></div>
<script charset="gb2312" th:src="@{/js/rule.js}" type="text/javascript"></script>
<script type="text/javascript">
    var prefix = ctx + "zzjx/pefctasstable"
    var data = [];
    $(function () {
        doChange();
        $.modal.closeLoading();
        debugger
        /*if($("#typeYB").val()==1){
            $('input[type="text"]').attr('disabled',true);
            $('input[type="radio"]').attr('disabled',true);
            $('textarea').attr('disabled',true);
            $('select').attr('disabled',true);
            $('input[type="text"]').prop('readonly',true);
            $('input[type="radio"]').prop('readonly',true);
            $('textarea').prop('readonly',true);
            $('select').prop('readonly',true);
        }*/
    })
    /**
     * 初始化表格信息
     */

    var formulaMap = null; //公式
    var dictData = null;	//表头 rule.js需要用到这两个，一定要声明为全局变量
    function doChange() {
        var id = $("#id").val();
        var tableId = $("#tableId").val(); //表单id
        if (tableId != "") {
            $.modal.loading("请等待加载预览信息!");
            $.ajax({
                url: ctx + "zzjx/pefctasstable/preview"
                , data: {"tableId": tableId, "id": id, "time": (new Date()).getTime()}
                , dataType: "JSON"
                , type: "GET"
                , async: false
                , success: function (result) {
                    $.table.destroy("table");
                    dictData = result.dictData;
                    formulaMap = result.formulaMap;
                    var list = result.list;
                    buildTable($('#table'), dictData.length, list.length, dictData, list);
                    data = dictData;
                    $.modal.closeLoading();
                }, error: function () {
                    $.modal.closeLoading();
                    $.modal.alertError("获取预览信息失败!");
                }
            })
            $("#tableDiv").removeClass("hidden");
            return false;
        }
        $("#tableDiv").addClass("hidden");
    }

    /*获取列头字段*/
    function getRows() {
        var rows = {};
        var roleId = $("#roleId").val();
        rows["id"] = guid();
        for (var dd in data) {
            var dictLabel = data[dd]["dictLabel"];//显示名称
            var dictValue = data[dd]["dictValue"];//字段值
            /*rows.push(f);*/
            rows[dictValue] = "";
        }
        return rows;
    }

    /**
     * 构建预览信息表格
     * @param $el        table对象
     * @param cells        列数
     * @param rows        行数
     * @param dictData    表头数据
     * @param list        行数据
     */
    function buildTable($el, cells, rows, dictData, list) {
        var i, j, row, columns = [], data = [];
        var isDisabled = false;
        if ($("#typeYB").val() == 1) {
            isDisabled = true;
        }
        var roleId = $("#roleId").val();
        columns.push({
            checkbox: true
        })
        columns.push({
            field: "id",
            title: "ID",
            visible: false
        })
        //拼接table,拼接表头
        for (var dd in dictData) {
            var dictLabel = dictData[dd]["dictLabel"];//显示名称
            var dictValue = dictData[dd]["dictValue"];//字段值
            var listClass = dictData[dd]["listClass"];//列显示类型(输入框，下拉框，显示)
            var isMustFill = dictData[dd]["isMustFill"];//是否为空
            var fillRoleIds = dictData[dd]["fillRoleIds"];//可评角色ID
            var f = {
                field: dictValue,
                title: dictLabel,
                sortable: false
            }
            var opt = {
                dictLabel: dictLabel,	//必填
                dictValue: dictValue,	//必填
                tableId: "table",		//必填
                ruleId: listClass,		//必填
                align: "center",
                halign: "center",
                isMustFill: isMustFill,	//必填
                isDisabled: isDisabled,
                fillRoleIds: fillRoleIds,//必填
                formId: "formTable",		//必填
            };
            f = $.rule.fmRule(opt);
            columns.push(f);
        }

        columns.push(
            {
                field: "scoringMethod",
                title: "公式ID",
                visible: false,
            }
        );
        /*columns.push({
            title: "操作",
            align: 'center',
            formatter: function(value, row, index) {
                var actions = [];
                actions.push('<a class="btn btn-success btn-xs" onclick="submitR(\'' + index + '\')"><i class="fa fa-check"></i>提交</a>');
                actions.push('<a style="margin-left:3px;" class="btn btn-success btn-xs" onclick="deleteR(\'' + index + '\')"><i class="fa fa-remove"></i>删除</a>');
                return actions.join('');
            }
        })*/
        //构建表格
        $el.bootstrapTable('destroy').bootstrapTable({
            columns: columns,
            data: list,
            uniqueId: "id",
            search: false,
            showSearch: false,
            showRefresh: false,
            showToggle: false,
            showColumns: false,
            showExport: false,                     //是否显示导出
            exportDataType: "basic",              //basic', 'all', 'selected'.
            height: 600,
            pagination: false,
            modalName: "考核指标",
            /*onDblClickCell:function(field,value,row,$element) {
                debugger
                var upIndex = $element[0].parentElement.rowIndex - 1;
                if (field == field) {
                    $element[0].innerHTML = "<input id='inputCell' type='text' name='inputCell' style ='width: 150px' value='" + value + "'>";
                    $("#inputCell").focus();
                    $("#inputCell").blur(function () {
                        var newValue = $("#inputCell").val();
                        row[field] = newValue;
                        $(this).remove();
                        $el.bootstrapTable('updateCell', {
                            index: upIndex,
                            field: field,
                            value: newValue
                        });
                        $.operate.rowedit(row);
                        // updateExbEnt();
                    });
                }
            },*/
            onPostBody: function (data) {
                /* bding();*/
            }
        });
    }

    /* 新增表格行 */
    function insertRow() {
        var arr = getRows();
        var len = $('#table').bootstrapTable('getData').length;
        $("#table").bootstrapTable('insertRow', {
            index: len + 1, // 你想插入到哪，0表示第一行
            row: arr
        })
        console.log(len);
    }

    function submitR(index) {
        var data = $("#table").bootstrapTable('getRowByIndex', index);//获取序号为0的数据
        console.log(eval(data));
    }

    function deleteR(index) {

    }

    function guid() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }

        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }

    function doSubmit() {
        debugger
        var rows = $("#table").bootstrapTable('getData').length;
        if (rows > 0) {
            var data = $("#form-kaoping").serializeArray();
            data.push({"name": "tableDataJson", "value": JSON.stringify($("#table").bootstrapTable('getData'))});
            if (!checkTableReq()) {
                $.modal.alertError("请将信息填写完整后提交!");
                return;
            }
            $.operate.saveTab(ctx + "zzjx/approver/doSubmit2Table", data);
        } else {
            $.modal.alertError("暂无数据可提交!");
            return;
        }
    }

    function checkTableReq() {
        var isOk = true;
        $("#table" + " .required").each(function () {
            var val = $(this).val();
            if (val == "") {
                isOk = false;
                return false;
            }
        });
        return isOk;
    }

    function doRemoveById() {
        var ids = $.map($('#table').bootstrapTable('getSelections'), function (row) {
            return row["id"];
        });
        if (ids.length == 0) {
            $.modal.alertWarning("请选择一条数据!");
            return false;
        } else {
            $.modal.confirm("确认是否删除已选中的数据？", function () {
                $("#table").bootstrapTable('remove', {
                    field: 'id',
                    values: ids
                })
            });
        }
    }

    function appealfun() {
        var approverId = $("#id").val();
        var roleId = $("#roleId").val();
        $.modal.loading("正在加载数据，请稍后...");
        var url = ctx + "zzjx/appealTab/toAppeal/" + approverId + "/" + roleId;
        debugger
        var _url = $.common.isEmpty(url) ? "/404.html" : url;
        var _height = ($(window).height() - 50);
        layer.open({
            type: 2,
            maxmin: true,
            shade: 0.3,
            title: '申诉管理',
            fix: false,
            area: [1199 + 'px', _height + 'px'],
            content: _url,
            shadeClose: false,
            btn: ['<i class="fa fa-close"></i> 关闭'],
            cancel: function () {
                return true;
            }
        });
        $.modal.closeLoading();
    }


    function importExcel() {
        layer.open({
            type: 1,
            area: ['400px', '230px'],
            fix: false,
            //不固定
            maxmin: true,
            shade: 0.3,
            title: '导入数据',
            content: $('#importForm'),
            btn: ['<i class="fa fa-check"></i> 导入', '<i class="fa fa-remove"></i> 取消'],
            // 弹层外区域关闭
            shadeClose: true,
            btn1: function (index, layero) {
                var file = layero.find('#file').val();
                if (file == '' || (!$.common.endWith(file, '.xls') && !$.common.endWith(file, '.xlsx'))) {
                    $.modal.msgWarning("请选择后缀为 “xls”或“xlsx”的文件。");
                    return false;
                }
                var index = layer.load(2, {shade: false});
                $.modal.disable();
                var formData = new FormData();
                formData.append("file", $('#file')[0].files[0]);
                formData.append("updateSupport", $("input[name='updateSupport']").is(':checked'));
                $.ajax({
                    url: prefix + "/ParseExcel",
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    type: 'POST',
                    success: function (data) {
                        for (i = 0; i < data.length; i++) {
                            var row = getRow(data[i]);
                            var len = $('#table').bootstrapTable('getData').length;
                            $("#table").bootstrapTable('insertRow', {
                                index: len + 1, // 你想插入到哪，0表示第一行
                                row: row
                            })
                        }
                        $.modal.closeAll();
                    }
                });
            }
        });
    }

    function getRow(list) {
        var rows = {};
        var roleId = $("#roleId").val();
        rows["id"] = guid();
        var a = 0;
        for (var dd in data) {
            var dictLabel = data[dd]["dictLabel"];//显示名称
            var dictValue = data[dd]["dictValue"];//字段值
            /*rows.push(f);*/
            rows[dictValue] = list[a++];
        }
        return rows;
    }
</script>
</body>
<form class="mt20 mb10" enctype="multipart/form-data" id="importForm" style="display: none;">
    <div class="col-xs-offset-1">
        <input id="file" name="file" type="file"/>
        <div class="mt10 pt5">
            <!--<input type="checkbox" id="updateSupport" name="updateSupport" title="如果指标体系已经存在，更新这条数据。"> 是否更新已经存在的指标体系数据-->
            &nbsp; <a class="btn btn-default btn-xs"
                      onclick="$('#table').tableExport({ type: 'excel', escape: 'false'})"><i class="fa fa-file-excel-o"></i> 下载模板</a>
        </div>
        <font class="pull-left mt10" color="red">
            提示：仅允许导入“xls”或“xlsx”格式文件！
        </font>
    </div>
</form>
</html>
